import { useEffect, useState, useRef, useContext } from "react";
import { fetchHomeChart, fetchAnomalyTrend } from "@/services/charts";
import { BigScreenContext } from "../../context/BigScreenContext";
import useAnomaly from "../../components/MainBody/hooks/useAnomaly";
import { getPosition } from "@/utils/position";

const POLLING_INTERVAL = 60 * 1000; // 60秒轮询间隔

// 定义接口返回的数据类型
export interface ChartDataItem {
  abnormalCause: string;
  currentState: number;
  evaluationItemId: string;
  predictTime?: string;
  evaluationItemName: string;
  groupType: number;
  tagDesc?: string;
  tagName: string;
  tagTimeAndValueMapping: Record<string, string>;
  upperLimit?: number;
  lowerLimit?: number;
}

// 定义趋势图数据类型
export interface TrendData {
  times: string[];
  values: number[];
  tagName?: string;
  tagDesc?: string;
  evaluationItemName?: string;
  abnormalCause?: string;
  currentState?: number;
  groupType?: number;
  predictTime?: string;
  upperLimit?: number;
  lowerLimit?: number;
}

// 定义参数模式的数据项类型
export interface ParamDataItem {
  tagName: string;
  tagValue: number;
  appTime: string;
}

const useCharts = (currentKey: string, activeTab: string) => {
  const { currentDevice, setCurrentDevice, currentPathDevice, paramJson } = useContext(BigScreenContext);
  const { selectedAnomaly, setSelectedAnomaly } = useAnomaly(); // 获取选中的异常
  const [chartData, setChartData] = useState<any>(null);
  const [trendData, setTrendData] = useState<TrendData[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);
  const timerRef = useRef<NodeJS.Timeout | null>(null);

  // 清除定时器的函数
  const clearPollingTimer = () => {
    if (timerRef.current) {
      clearInterval(timerRef.current);
      timerRef.current = null;
    }
  };

  // 处理趋势图数据
  const processTrendData = (data: ChartDataItem[]) => {
    if (!data || !Array.isArray(data)) return [];

    return data.map(item => {
      const timeValueMap = item.tagTimeAndValueMapping || {};
      // 将时间和值的映射转换为有序数组
      const timeEntries = Object.entries(timeValueMap)
        .sort(([timeA], [timeB]) => new Date(timeA).getTime() - new Date(timeB).getTime());

      // 提取时间和值
      const times = timeEntries.map(([time]) => time);
      const values = timeEntries.map(([_, value]) => parseFloat(value));

      return {
        times,
        values,
        tagName: item.tagName,
        predictTime: item.predictTime,
        upperLimit: item.upperLimit,
        lowerLimit: item.lowerLimit,
        tagDesc: item.tagDesc,
        position: getPosition(item.tagDesc ?? ''),
        evaluationItemName: item.evaluationItemName,
        abnormalCause: item.abnormalCause,
        currentState: item.currentState,
        groupType: item.groupType
      };
    });
  };

  const processAnomalyTrendData = (data: any, description?: string) => {
    const timeEntries = Object.entries(data.tagTimeAndValueMapping)
      .sort(([timeA], [timeB]) => new Date(timeA).getTime() - new Date(timeB).getTime());

    // 提取时间和值
    const times = timeEntries.map(([time]) => time);
    const values = timeEntries.map(([_, value]) => parseFloat(value as string));

    return {
      times,
      values,
      upperLimit: data?.upperLimit,
      lowerLimit: data?.lowerLimit,
      predictTime: data?.predictTime,
      abnormalCause: description,
      evaluationItemName: data?.evaluationItemName,
      tagName: data?.tagName,
      groupType: data?.groupType,
    }
  };

  // 处理参数模式的数据
  const processParamData = (paramData: any, currentDeviceParams: string) => {
    if (!paramData || !paramData.step2DTO || !(paramData.step2DTO?.cotARateList?.length) || !(paramData.step2DTO?.cotBRateList?.length)) return [{
      times: [],
      values: [],
      tagName: '',
      evaluationItemName: currentDeviceParams,
      tagDesc: '',
      currentState: 10,
    }];

    const { cotARateList, cotBRateList } = paramData.step2DTO;
    const result: TrendData[] = [];

    // 处理cotARateList
    if (cotARateList && Array.isArray(cotARateList) && cotARateList.length > 0) {
      const tagName = cotARateList?.[0]?.tagName;
      const times = cotARateList?.map(item => item.appTime);
      const values = cotARateList?.map(item => item.tagValue);
      const tagDesc = cotARateList?.[0]?.tagDesc;
      result.push({
        times,
        values,
        tagName,
        evaluationItemName: currentDeviceParams,
        currentState: 10,
        tagDesc
      });
    }

    // 处理cotBRateList
    if (cotBRateList && Array.isArray(cotBRateList) && cotBRateList.length > 0) {
      const tagName = cotBRateList?.[0]?.tagName;
      const times = cotBRateList?.map(item => item.appTime);
      const values = cotBRateList?.map(item => item.tagValue);
      const tagDesc = cotBRateList?.[0]?.tagDesc;

      result.push({
        times,
        values,
        tagName,
        evaluationItemName: currentDeviceParams,
        currentState: 10,
        tagDesc
      });
    }
    return result;
  };

  // 获取问题模式下的图表数据
  const fetchQuestionData = async () => {
    try {
      setLoading(true);
      setError(null);

      // 根据条件构造不同的请求参数
      const requestData = {
        groupType: [11, 12],
      };

      const res = await fetchHomeChart(requestData);

      // 检查接口响应状态
      if (res.status) {
        setChartData(res.content);

        // 处理趋势图数据
        if (res.content && Array.isArray(res.content)) {
          const processedData = processTrendData(res.content);
          setTrendData(processedData);
        }
      } else {
        setError(res.message || '获取数据失败');
      }
    } catch (err: any) {
      setError(err.message || '请求出错');
      console.error('获取图表数据出错:', err);
    } finally {
      setLoading(false);
    }
  };

  // 获取异常模式下的趋势图数据
  const fetchAnomalyData = async () => {
    if (!selectedAnomaly) {
      console.log('没有选中的异常，无法获取趋势数据');
      return;
    }

    try {
      setLoading(true);
      setError(null);
      console.log('selectedAnomaly', selectedAnomaly);
      // 根据selectedAnomaly构造请求参数
      const requestData = {
        evaluationItemName: selectedAnomaly.evaluationItemName,
        tagName: selectedAnomaly.code,
      };

      console.log('请求异常趋势数据，参数:', requestData);

      const res = await fetchAnomalyTrend(requestData);

      // 检查接口响应状态
      if (res.status) {
        // 处理趋势图数据
        console.log('res.content', res.content);
        const processedData = processAnomalyTrendData(res.content, selectedAnomaly?.description);
        setTrendData([processedData]);
        console.log('异常趋势数据获取成功:', processedData);
      } else {
        setError(res.message || '获取异常趋势数据失败');
        console.error('获取异常趋势数据失败:', res.message);
      }
    } catch (err: any) {
      setError(err.message || '请求出错');
      console.error('获取异常趋势数据出错:', err);
    } finally {
      setLoading(false);
    }
  };

  // 启动轮询
  const startPolling = () => {
    // 确保不会创建多个定时器
    clearPollingTimer();

    // 立即获取一次数据
    fetchQuestionData();

    // 设置定时器，每60秒轮询一次
    timerRef.current = setInterval(fetchQuestionData, POLLING_INTERVAL);
  };

  // 监听currentKey和activeTab变化，控制轮询
  useEffect(() => {
    console.log("currentKey 监听", currentKey);
    console.log("activeTab 监听", activeTab);

    // 当条件满足时开始轮询
    if (activeTab === "裂解炉" && currentKey === "question") {
      console.log("开始轮询");
      startPolling();
    } else {
      // 不满足条件时清除轮询
      clearPollingTimer();

      // 不是question模式时清空trendData
      if (currentKey !== 'anomaly' && currentKey !== 'param') {
        setTrendData([]);
        console.log("不是question或anomaly或param模式，清空trendData");
      }
    }
    if (activeTab !== "裂解炉") {
      setSelectedAnomaly(null);
    }
    // 组件卸载时清除定时器
    return () => {
      clearPollingTimer();
    };
  }, [currentKey, activeTab]);

  // 监听selectedAnomaly变化，在anomaly模式下获取趋势数据
  useEffect(() => {
    // 只在anomaly模式下监听selectedAnomaly变化
    if (currentKey === 'anomaly' && selectedAnomaly) {
      console.log("selectedAnomaly变化，获取趋势数据", selectedAnomaly.id);
      fetchAnomalyData();
    }
    if (currentKey === "param") {
      console.log("paramJson.step2DTO变化", paramJson?.step2DTO);
      console.log("currentDevice变化", currentDevice);
      const paramTrendData = processParamData(paramJson, currentDevice);
      setTrendData(paramTrendData);
    }
  }, [selectedAnomaly, currentKey, paramJson, currentDevice]);

  return {
    currentDevice,
    setCurrentDevice,
    currentPathDevice,
    chartData,
    trendData,  // 返回处理后的趋势图数据
    loading,
    error,
    refreshData: currentKey === 'anomaly' ? fetchAnomalyData : fetchQuestionData  // 根据模式提供不同的刷新方法
  };
};

export default useCharts;

